﻿using System;
using System.Web.UI.WebControls;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using Cms.Utilities;
using Cms.Web.Framework.Controls;

namespace Cms.Web.Framework.Plugins
{
    public class WriteComment : BaseTemplatedPlugin
    {
        // Property fields
        // Template controls
        private TextBox txtComment;
        private TextBox txtName;
        private ValidationSummary vsErrors;

        public int ContentID { get; set; }
        
        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();
                vsErrors = (ValidationSummary)FindControl("vsErrors");
                txtComment = (TextBox)FindControl("txtComment");
                txtName = (TextBox)FindControl("txtName");
                var btnSave = (Button)FindControl("btnSave");
                btnSave.Click += btnSave_Click;
            }
            catch (Exception ex)
            {
                Logging.LogError("WriteComment", ex);
                Controls.Clear();
            }
        }
        
        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void Save()
        {
            if (txtName.Text.Trim() == string.Empty)
            {
                var lplNoNameErrorMessage = (LocalizedPluginLiteral)FindControl("lplNoNameErrorMessage");
                AddError(lplNoNameErrorMessage.Text, "WriteComment");
            }
            if (txtComment.Text.Trim() == string.Empty)
            {
                var lplNoCommentErrorMessage = (LocalizedPluginLiteral)FindControl("lplNoCommentErrorMessage");
                AddError(lplNoCommentErrorMessage.Text, "WriteComment");
            }
            if (!Page.IsValid)
                return;
            IContentRepository contentRepository = new ContentRepository();
            var comment = new Comment();
            comment.Approved = true;
            comment.Created = DateTime.Now;
            comment.Locale = RequestDetails.Locale;
            comment.Name = txtName.Text;
            comment.Text = txtComment.Text;

            //comment.Member =
            if (ContentID > 0)
            {
                comment.Content = contentRepository.GetContent(ContentID);
                comment.Content.Comments.Add(comment);
            }
            else
            {
                comment.Page = RequestDetails.Page;
                comment.Page.Comments.Add(comment);
            }
            IPageRepository pageRepository = new PageRepository();
            pageRepository.SaveComment(comment);

            //Clean up
            txtName.Text = string.Empty;
            txtComment.Text = string.Empty;
        }
    }
}